﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SPVisualDev
{
    public partial class DialogTreeSelector : Form
    {
        private string _path = string.Empty;
        private string _checked_nodes = string.Empty;

        public DialogTreeSelector()
        {
            InitializeComponent();

            this.TreeView.AfterCheck += new TreeViewEventHandler(TreeView_AfterCheck);
        }

        void TreeView_AfterCheck(object sender, TreeViewEventArgs e)
        {
            try
            {
                RecursiveCheckUncheck(e.Node, e.Node.Checked);
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        public string CheckedNodes
        {
            get
            {
                _path = string.Empty;
                ProcessOneNode(this.TreeView.TopNode, 2);

                return _checked_nodes;
            }
            set
            {
                _path = string.Empty;
                _checked_nodes = value;
                if (_checked_nodes == null)
                    _checked_nodes = string.Empty;

                ProcessOneNode(this.TreeView.TopNode, 1);
            }
        }

        private void ProcessOneNode(TreeNode Node, int Mode)
        {
            foreach (TreeNode visit_node in Node.Nodes)
            {
                if (visit_node.Nodes.Count > 0)
                {
                    if (_path == string.Empty)
                        _path += visit_node.Name;
                    else
                        _path += "/" + visit_node.Name;

                    ProcessOneNode(visit_node, Mode);
                }

                if (Mode == 1)
                {
                    if (!string.IsNullOrEmpty(_path))
                    {
                        if (_checked_nodes.IndexOf(_path + "/" + visit_node.Name + ";") != -1)
                            visit_node.Checked = true;
                    }
                }
                else
                {
                    if (visit_node.Checked)
                        _checked_nodes += _path + "/" + visit_node.Name + ";";
                }
            }
        }

        private void RecursiveCheckUncheck(TreeNode Node, bool Checked)
        {
            foreach (TreeNode visit_node in Node.Nodes)
            {
                if (visit_node.Nodes.Count > 0)
                    RecursiveCheckUncheck(visit_node, Checked);

                visit_node.Checked = Checked;
            }
        }
    }
}
